package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author: taoyi
 * @date: 2021/6/16 20:14
 * @version: 1.0
 * @explain:
 */
@Service
public class ItemServiceImpl implements ItemService{

    @Autowired(required = false)
    private ItemDescMapper itemDescMapper;

    @Autowired(required = false)
    private ItemMapper itemMapper;

    @Override
    public PageResult getItemList(PageResult pageResult) {
        // 1.定义分页对象
        IPage page = new Page(pageResult.getPageNum(), pageResult.getPageSize());
        // 构建查询的条件构造器
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        Boolean flag = StringUtils.hasLength(pageResult.getQuery());
        // 根据判断条件决定是否拼接where条件
        queryWrapper.like(flag,"title",pageResult.getQuery());
        // MP提供的分页查询的方法，返回值是Page对象，其中包含分页的结果信息
        page = itemMapper.selectPage(page, queryWrapper);
        long total = page.getTotal();
        // MP帮助实现了数据的查询
        List<Item> records = page.getRecords();
        return pageResult.setRows(records).setTotal(total);
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    /**
     * 完成2张表的入库操作
     * 1.item表
     * 2.item_desc表
     * @param itemVO
     */
    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        // 1.获取商品对象
        Item item = itemVO.getItem();
        item.setStatus(true);
        // MP已经实现了主键的自动回显，ID是入库后回显的
        itemMapper.insert(item);
        // 2.获取商品详情
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);


    }
}
